<template>
    <div class="flex_row">
        <div class="flex_col m5 p10">
            <div class="flex_row_center mt5">
                <label class="dlb">名称</label>
                <el-input v-model="form.name" clearable class="dinput"/>
            </div>
            <div class="flex_row_center mt5">
                <label class="dlb">MAC地址</label>
                <el-input v-model="form.mac_addr" clearable class="dinput"/>
            </div>
            <div class="flex_row_center mt5">
                <el-button @click="onClickUpdate" type="primary">更新</el-button>
                <el-button @click="onClickDelete" type="warning">删除</el-button>
            </div>
        </div>
    </div>
</template>

<script lang="ts" setup>

import { runAction } from '@/utils/ui';
import { reactive, watch } from 'vue';
import device from '@/service/device';
import { deviceUpdate, selectDevice } from '@/utils/react';

interface FormCtx {
    name: string,
    mac_addr: string,
}

const form = reactive<FormCtx>({
    name: '',
    mac_addr: '',
});

watch(selectDevice, () => {
    const info = selectDevice.value;
    if (info == null) {
        return;
    }
    form.name = info.name!!;
    form.mac_addr = info.mac_addr;
});

async function onClickDelete() {
    runAction('设备', '删除', async () => {
        const info = selectDevice.value;
        if (info == null) {
            throw '请选择需要修改的设备';
        }
        await device.delete(info.id);
        await deviceUpdate();
    });
}

async function onClickUpdate() {
    runAction('设备', '更新', async () => {
        const info = selectDevice.value;
        if (info == null) {
            throw '请选择需要修改的设备';
        }
        if (form.name.length == 0) {
            throw '请输入设备名称';
        }
        if (form.mac_addr.length == 0) {
            throw '请输入设备MAC地址';
        }
        await device.update(info.id, {
            name: form.name,
            language: null,
            location: null,
        });
        await deviceUpdate();
    });
}

</script>

<style scoped>

.dinput {
    min-width: 120px;
    width: 18vw;
    max-width: 300px;
}

.dlb {
    width: 70px;
}

</style>
